package utilities;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import javax.swing.JOptionPane;

import org.jgroups.Address;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.Receiver;
import org.jgroups.View;
import org.jgroups.logging.Log;
import org.jgroups.protocols.UDP;

public class TransportDriver extends JChannel implements Receiver{
	private String clusterName;
	private String userName;
	private TransportReceiver transportReceiver;
	private static Log logger;
	private JChannel drvChannel;
	private static int port = 666;
	private Address srcAddr = null, dstAddr = null;
	
	
	public TransportDriver( String userName, final String clusterName, TransportReceiver transportReceiver) throws Exception{
		logger.debug("Forcing to IpV4 stack"); //think of using log4j for logging important information 
		System.setProperty("java.net.preferIPv4Stack",    "true"); 
		System.setProperty("jgroups.bind_addr", "127.0.0.1" );
		this.userName = userName;
		this.clusterName = clusterName;
		this.transportReceiver = transportReceiver;

		try{
			drvChannel = new JChannel();
			UDP protocol = (UDP)drvChannel.getProtocolStack().getTransport();
			
			if (getPort() !=0)
			protocol.setMulticastPort(getPort());
			else
	
	
			JOptionPane.showMessageDialog(null, "can't find a port, default is used");
			drvChannel.connect(clusterName);
			drvChannel.setReceiver(this); 
			drvChannel.setDiscardOwnMessages(true);
			srcAddr = drvChannel.getAddress();
			
		}
		catch (Exception e){
			logger.error("<<class Abstract Channel Driver>>can not create channel ");
		}

	}

	/**
	 * Avoid conflict when establishing multiple connexions
	 * @return useable port
	 */
	private int getPort() {
		return port+=1;
	}

	public void sendMessage(MessageType type, Object content) throws Exception {
		ChatMessage msg = new ChatMessage(type, srcAddr, dstAddr, content, userName);
		drvChannel.send(dstAddr, msg);
	}
	@Override
	public void getState(OutputStream arg0) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	/**
	 * todo : implementation
	 */
	public void receive(Message arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setState(InputStream arg0) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void block() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void suspect(Address arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void unblock() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void viewAccepted(View view) {
		System.out.println("View: "+ view);
		/*
		 
		final ChatMessage chatMsg = new ChatMessage(vect);
		// Fill in message fields as appropriate 
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
		public void run() {
		if (drvChannel.getAddress()!=null) 
			transportReceiver.receiveChatMessage(chatMsg);
		}
		});

		*/
	}

	
}
